package com.snmp.smn.manager;

import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.Timer;

import com.snmp.smn.db.DBHelper;
import com.snmp.smn.utils.TimeConstants;
import com.snmp.smn.utils.Utilities;

public class StartManager {
	
	private StartManager(String dbConfig) throws Exception {
		Utilities.log("Starting Manager for Self Managing Networks.....");
		
		initDB(dbConfig);
		
		initServerSocket();
		
		monitorAgents();
		
		monitorDevices();
		
		Utilities.log("Manager for Self Managing Networks started.");
	}
	
	private void initServerSocket() {
		Utilities.log("Opening socket at : " + 10000);
		
		Thread socketThread = new Thread() {
			@Override
			public void run() {
				try {
					ServerSocket serverSocket = new ServerSocket(10000);
					while(true) {
						Socket socket = serverSocket.accept();
						Utilities.log("Accepted connection from " + socket.getRemoteSocketAddress());
						new MessageProcessor(socket).start();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		socketThread.start();
		
		Utilities.log("Socket opened at : " + 10000);
	}

	private void initDB(String dbConfig) throws Exception {
		Utilities.log("Initializing DB with config : " + dbConfig);
		
		File dbConfigFile = new File(dbConfig);
		if (!dbConfigFile.exists()) {
			Utilities.log("DB config " + dbConfig + " does not exists");
			System.exit(1);
		}
	
		Properties props = new Properties();
		props.loadFromXML(new FileInputStream(dbConfigFile));
		
		DBHelper.init(props.getProperty("database_host"), props.getProperty("database_port"), 
						props.getProperty("database_sid"), props.getProperty("database_username"),
							props.getProperty("database_password"));
		
		Utilities.log("DB Initialized.");
	}
	
	private void monitorAgents() throws Exception {
		Utilities.log("Initializing agents monitor");
		
		Timer timer = new Timer("Agents Monitor Timer");
		timer.schedule(new AgentsMonitorTask(), 5 * TimeConstants.SECOND, 
													30 * TimeConstants.SECOND);
		
		Utilities.log("Agents monitor initialized");
	}
	
	private void monitorDevices() throws Exception {
		Utilities.log("Initializing devices monitor");
		
		Timer timer = new Timer("Devices Monitor Timer");
		timer.schedule(new DevicesMonitorTask(), 5 * TimeConstants.SECOND, 
													30 * TimeConstants.SECOND);
		
		Utilities.log("Devices monitor initialized");
	}

	public static void main(String[] args) throws Exception {
		if (args.length != 1) {
			usage();
			System.exit(1);
		}
		
		new StartManager(args[0]);
	}
	
	private static void usage() {
		System.out.println("java -jar manager.jar <db-config-xml>");
	}
}
